package com.sky.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    /**
     * 生成JWT
     *
     * @param secretKey
     * @param ttlMillis
     * @param claims
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String createJWT(String secretKey, long ttlMillis, Map<String, Object> claims) throws UnsupportedEncodingException {
        //1.指定签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//2.JWT过期时间=现在时间+ttlMillis
        long expMillis = System.currentTimeMillis() + ttlMillis;
        //转换为Date类型
        Date exp = new Date(expMillis);
//3.生成JWT,claim是自定义的键值对
        String compact = Jwts.builder()
                .setClaims(claims)
                .setExpiration(exp)
                .signWith(signatureAlgorithm, secretKey.getBytes("UTF-8"))
                .compact();
        return compact;

    }

    /**
     * 解析JWT
     *
     * @param secretKey
     * @param token
     * @return
     */
    public static Claims parseJwt(String secretKey, String token) {
        //1.给出秘钥和要解析的token
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token).getBody();
        return claims;
    }
}
